package com.yang.service.impl;

import com.yang.constant.ConfiConstant;
import com.yang.dao.CheckInDao;
import com.yang.dao.LoginDao;
import com.yang.entity.*;
import com.yang.pojo.CompanionDto;
import com.yang.service.CheckInService;
import com.yang.util.SnowFlake;
import org.aspectj.weaver.ast.Or;
import org.jboss.logging.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CheckInServiceImpl implements CheckInService {
    public static Logger logger = Logger.getLogger(CheckInServiceImpl.class);
    @Resource
    CheckInDao checkInDao;
    @Resource
    LoginDao loginDao;
    @Override
    public Map<String, Object> selectMoneyService(String roomNum, String preDay) {
        Map<String,Object> map = new HashMap<String, Object>();
        List<RoomEntity> roomEntities = loginDao.selectRoomEntity();
        RoomEntity roomEntity = null;
        for(RoomEntity room : roomEntities){
            if(room.getRoomNum().equals(roomNum)){
                roomEntity = room;
                break;
            }
        }
        if(roomEntity == null){
            map.put("status","error");
            map.put("info","房号出错");
            logger.error("在数据库没有找到房间号");
            return map;
        }
        if(roomEntity.getStatus().equals("1")){
            map.put("status","error");
            map.put("info","房间已被使用，请选择其他房号！");
            logger.error("房间已被使用");
            return map;
        }
        List<RateEntity> list = null;
        try{
            list =  checkInDao.selectMoneyByroomNum(roomNum);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("rate表查询出错！");
        }
        if(list == null || list.size() == 0){
            map.put("status","error");
            map.put("info","网络出错");
            logger.error("在数据库没有找到");
            return map;
        }
        logger.info("RateEntity = "+list.get(0).toString());
        int day = Integer.parseInt(preDay);
        float money = list.get(0).getMoney();
        float perpay = list.get(0).getPrepay();
        if(day <= 0){
            map.put("status","error");
            map.put("info","入天数不能小于0");
            logger.error("入住天数小于0");
            return map;
        }
        float pay = money*(day-1)+perpay;
        float sum = money*day;
        List<Float> list1 = new ArrayList<Float>();
        list1.add(pay);
        list1.add(sum);
        map.put("status","succeed");
        map.put("info",list1);
        return map;
    }

    @Override
    public Map<String, Object> resideservice(List<CompanionDto> companionDtos, String pay,long beginDay,HttpServletRequest request) {
        Map<String,Object> map = new HashMap<String, Object>();
        Long userId = (Long) request.getSession().getAttribute("id");
        if(userId == null){
            map.put("status","error");
            map.put("info","网络出错，请重新登陆！");
            logger.info("在session中未找到操作用户");
            return map;
        }
//        long userId = 886848415466497L;

        //获取居住的房间
        List<RoomEntity> roomEntities = loginDao.selectRoomEntity();
        RoomEntity roomEntity = null;
        for(RoomEntity room : roomEntities){
            if(room.getRoomNum().equals(companionDtos.get(0).getRoomNum())){
                roomEntity = room;
                break;
            }
        }
        if(roomEntity == null){
            map.put("status","error");
            map.put("info","房号出错");
            logger.error("在数据库没有找到房间号");
            return map;
        }
        if(roomEntity.getStatus().equals("1")){
            map.put("status","error");
            map.put("info","房间已被入住，请选择其他房号！");
            logger.error("房间已经被入住了");
            return map;
        }

        //旅客实体
        List<GuestEntity> guestEntities = new ArrayList<GuestEntity>();
        SnowFlake snowFlake = new SnowFlake(4,1);
        for(CompanionDto companionDto : companionDtos){
            GuestEntity guestEntity = new GuestEntity();
            guestEntity.setId(snowFlake.getId());
            String name = companionDto.getGuestName();
            if(name == null || name.equals("")){
                map.put("status","error");
                map.put("info","旅客名不能为空！");
                logger.info("旅客名不能为空");
                return map;
            }
            guestEntity.setName(name);
            guestEntity.setTel(companionDto.getTel());
            String identification = companionDto.getIdentity();
            if(identification == null || identification.equals("")){
                map.put("status","error");
                map.put("info","旅客身份证不能为空！");
                logger.info("旅客身份证为空");
                return map;
            }
            guestEntity.setIdetifcation(identification);
            guestEntity.setStatus("0");
            guestEntities.add(guestEntity);
        }
        guestEntities.get(0).setStatus(ConfiConstant.HOMEOWNER); //房主状态为1，其他同伴为0

        //订单实体
        List<RateEntity> rateEntities = null;
        try{
            rateEntities = checkInDao.selectMoneyByroomNum(companionDtos.get(0).getRoomNum());
        }catch (Exception e){
            e.printStackTrace();
            logger.error("找不到RateEntity");
            map.put("status","error");
            map.put("info","网络出错");
            return map;
        }
        RateEntity rateEntity = rateEntities.get(0);   //获取rate
        int stayDay = Integer.parseInt(companionDtos.get(0).getPerDay());
        if(stayDay<=0){
            map.put("status","error");
            map.put("info","最少需居住一天");
            logger.error("stayDay <=0");
            return map;
        }

        //long beginDay = System.currentTimeMillis();
        float prepay = rateEntity.getMoney()*(stayDay-1)+rateEntity.getPrepay();
        float rantal = rateEntity.getMoney()*stayDay;
        float  truePay = Float.parseFloat(pay);
        if(truePay<0){
            map.put("status","error");
            map.put("info","请付款");
            logger.error("truePay <=0");
            return map;
        }
        OrderFormEntity orderFormEntity = new OrderFormEntity(snowFlake.getId(),beginDay,stayDay,prepay,rantal,truePay);


        //liver_relation实体
        List<LiverRelationEntity> liverRelationEntities = new ArrayList<LiverRelationEntity>();
        for(GuestEntity guestEntity : guestEntities){
            LiverRelationEntity liverRelationEntity = new LiverRelationEntity();
            liverRelationEntity.setId(snowFlake.getId());
            liverRelationEntity.setUserId(userId);
            liverRelationEntity.setRoomId(roomEntity.getId());
            liverRelationEntity.setGuestId(guestEntity.getId());
            liverRelationEntity.setOrderFormId(orderFormEntity.getId());
            liverRelationEntity.setStatus("1");
            liverRelationEntities.add(liverRelationEntity);
        }

        //更新房间信息
        roomEntity.setStatus("1");
        if(!checkInDao.updataRoom(roomEntity)){
            logger.error("房间信息更改失败 = "+roomEntity.toString());
        }

        //保存顾客
        for(GuestEntity guestEntity : guestEntities){
            if(!checkInDao.saveGuest(guestEntity)){
                logger.error("旅客保存失败 = "+guestEntity.toString());
            }
        }

        //保存订单
        if(!checkInDao.saveOrderForm(orderFormEntity)){
            logger.error("订单保存失败 = "+orderFormEntity);
        }
        //保存居住关系

        for(LiverRelationEntity liverRelationEntity : liverRelationEntities){
            if(!checkInDao.saveLiverRelation(liverRelationEntity)){
                logger.error("居住关系保存失败 = "+liverRelationEntity.toString());
            }
        }
        map.put("status","susseed");
        map.put("info","登记成功！应预付："+prepay+"   实际需付："+rantal+"  实际付款："+truePay);
        return map;
    }

}
